package com.project.class8_23.lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class RWTest {
    public static void main(String[] args) throws InterruptedException {
        RWObj obj = new RWObj();
        new Thread(new Runnable() {
            @Override
            public void run() {
                obj.write();
            }
        }).start();
        Thread.sleep(100);
        new Thread(new Runnable() {
            @Override
            public void run() {
                obj.read();
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                obj.read();
            }
        }).start();
    }
}



class RWObj{

    private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    public void read(){
        //申请读锁
        rwLock.readLock().lock();
        try{
            for(int i=0;i<10;i++){
                System.out.println("读锁："+Thread.currentThread()+"    "+i);
                Thread.sleep(100);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //释放读锁
            rwLock.readLock().unlock();
        }
    }

    public void write(){
        //加写锁
        rwLock.writeLock().lock();
        try{
            for(int i=0;i<10;i++){
                System.out.println("写锁："+Thread.currentThread()+"  "+i);
                Thread.sleep(100);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            //释放写锁
            rwLock.writeLock().unlock();
        }
    }
}
